package com.miyake.dsp;

import java.util.ArrayList;
import java.util.List;

import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.javasci.JavasciException.InitializationException;
import org.scilab.modules.javasci.Scilab;
import org.scilab.modules.types.ScilabDouble;

import com.miyake.rest.DataColumn;
import com.miyake.rest.WebServiceProperty;

public class ScilabEngine {

	private static ScilabEngine instance = null;
	private static Scilab scilab = null;
	
	private ScilabEngine() {
		try {
			scilab = new Scilab();
			scilab.open();
		} catch (InitializationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JavasciException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public static synchronized ScilabEngine getInstance() {
		if (instance == null) {
			instance = new ScilabEngine();
		}
		return instance;
	}

	public synchronized WebServiceProperty process(WebServiceProperty prop) throws JavasciException {
		scilab.exec("clear");
		sendInputData(toComplexArray(prop.getData()));
		scilab.exec(prop.getValues().get(0).getValue());
		ScilabDouble ret = (ScilabDouble)scilab.get("ret");
		
		WebServiceProperty prop2 = WebServicePropertyBuilder.getInstance().get();
		double[] real = ret.getRealPart()[0];
		String[] realString = new String[real.length];
		for (int i = 0; i < real.length; i++) {
			realString[i] = String.valueOf(real[i]);
		}
		prop2.getData().add(new DataColumn("Real Part", realString));
		if (ret.getImaginaryPart().length > 0) {
			double[] imag = ret.getImaginaryPart()[0];
			String[] imagString = new String[imag.length];
			for (int i = 0; i < imag.length; i++) {
				imagString[i] = String.valueOf(imag[i]);
			}
			prop2.getData().add(new DataColumn("Imaginary Part", imagString));
		}
		
		
		return prop2;
	}

	public List<ComplexArray> toComplexArray(List<DataColumn> columns) {
		List<ComplexArray> ret = new ArrayList<ComplexArray>();
		for (DataColumn dataColumn : columns) {
			ret.add(new ComplexArray(toDoubleArray(dataColumn.getDataArray())));
		}
		return ret;
	}
	
	private double[] toDoubleArray(String[] dataArray) {
		double[] ret = new double[dataArray.length];
		int i = 0;
		for (String s : dataArray) {
			ret[i++] = Double.valueOf(s);
		}
		return ret;
	}

	private void sendInputData(List<ComplexArray> dataList) {	
		int i = 1;
		for (ComplexArray data : dataList) {
			double[][] real = new double[1][data.getRealPart().length];
			real[0] = data.getRealPart();
			
			double[][] imag = null;
			if (data.getImagPart() != null) {
				imag = new double[1][data.getImagPart().length];
				imag[0] = data.getImagPart();
			}
			try {
				String num = String.valueOf(i++);
				scilab.put("data" + num, new ScilabDouble(real, imag));
			} catch (JavasciException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
